package com.miku.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miku.common.ErrorCode;
import com.miku.constant.CommonConstant;
import com.miku.exception.BusinessException;
import com.miku.exception.ThrowUtils;
import com.miku.mapper.CreditMapper;
import com.miku.model.dto.credit.CreditQueryRequest;
import com.miku.model.entity.Credit;
import com.miku.service.CreditService;
import com.miku.utils.RedissonLockUtil;
import com.miku.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
* @author ThinkBook
* @description 针对表【credit(积分表)】的数据库操作Service实现
* @createDate 2024-07-15 15:31:42
*/
@Service
public class CreditServiceImpl extends ServiceImpl<CreditMapper, Credit>
    implements CreditService{

    @Resource
    private RedissonLockUtil redissonLockUtil;
    /**
     *
     * 根据条件查询积分信息
     * @param creditQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Credit> getQueryWrapper(CreditQueryRequest creditQueryRequest) {

        QueryWrapper<Credit> queryWrapper = new QueryWrapper<>();
        if (creditQueryRequest == null) {
            return queryWrapper;
        }

        Long id = creditQueryRequest.getId();
        Long userId = creditQueryRequest.getUserId();
        Long creditTotal = creditQueryRequest.getCreditTotal();
        String sortField = creditQueryRequest.getSortField();
        String sortOrder = creditQueryRequest.getSortOrder();
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(creditTotal), "creditTotal", creditTotal);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public Boolean consumeCredits(Long userId, long credits) {

        //锁名称
        String lockName="credit:consume:"+userId;
       return redissonLockUtil.redissonDistributedLocks(lockName,()->{
           if (userId == null){
               throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
           }
           QueryWrapper<Credit> queryWrapper = new QueryWrapper<>();
           queryWrapper.eq("userId",userId);
           Credit credit = this.getOne(queryWrapper);
           ThrowUtils.throwIf(credit == null, ErrorCode.NOT_FOUND_ERROR);
           Long creditTotal = credit.getCreditTotal();
           //积分不足时
           if (creditTotal<=0) return false;
           creditTotal =creditTotal + credits;
           credit.setCreditTotal(creditTotal);
           //保持更新时间
           credit.setUpdateTime(null);
           return this.updateById(credit);
       },"积分消费失败");
    }
}




